import re
import sys
import datetime
from mysql import MyMysql
from PySide6.QtCore import Qt
from PySide6.QtGui import QIcon
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from exam import MainWindow
from connect import User, Device, Order, Base

class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        self.mysql = MyMysql()
        # 连接数据库
        uname = "root"
        pwd = "123456"
        host = "127.0.0.1"
        port = "3306"
        db = "798"
        self.engine = create_engine(f"mysql+pymysql://{uname}:{pwd}@{host}:{port}/{db}")
        # 创建base 模型类对象
        base = Base()
        # 创建所有的表
        base.metadata.create_all(self.engine)
        Session = sessionmaker(bind=self.engine)
        self.session = Session()

        self.setStyleSheet("background-color:#00BFFF")
        # 设置新窗口
        self.setWindowTitle('798管理平台')
        self.resize(1200, 600)
        self.setContentsMargins(480, 200, 200, 200)

        stacked_widget = QStackedWidget()

        # 设置登录窗口
        v_layout = QVBoxLayout()
        v_layout.setAlignment(Qt.AlignVCenter)
        form_layout = QFormLayout()
        label = QLabel('798登录注册')
        font = QFont()
        font.setPointSize(17)
        label.setFont(font)
        form_layout.addRow(label)
        # 设置颜色为灰色
        palette = label.palette()
        palette.setColor(QPalette.WindowText, Qt.gray)
        label.setPalette(palette)
        #  创建一条水平线
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setFrameShadow(QFrame.Shadow.Sunken)
        line.setStyleSheet('background-color:rgb(200, 200, 198)')
        line.setFixedHeight(1)  # 设置水平线的高度
        # 将水平线加到主窗口的中心布局中
        form_layout.addRow(line)

        self.name = QLineEdit('')
        self.name.setPlaceholderText('用户名')
        self.name.setStyleSheet('background-color:#FFFFFF;color:gray;border:none;padding-left:5px;border-radius:5px')
        self.name.setFixedHeight(40)
        # 图标
        icon = QIcon('用户.png')
        u_action = QAction(self.name)
        u_action.setIcon(icon)
        self.name.addAction(u_action, QLineEdit.ActionPosition.TrailingPosition)
        form_layout.addRow(self.name)

        self.password = QLineEdit('')
        self.password.setPlaceholderText("密码")
        self.password.setEchoMode(QLineEdit.Password)  # 密码加密
        self.password.setStyleSheet(
            'background-color:#FFFFFF;color:gray; border:none;padding-left:5px;border-radius:5px')
        self.password.setFixedHeight(40)
        # 图标
        icon = QIcon('密码.png')
        u_action = QAction(self.password)
        u_action.setIcon(icon)
        self.password.addAction(u_action, QLineEdit.ActionPosition.TrailingPosition)
        form_layout.addRow(self.password)

        login_btn = QPushButton('登录')
        login_btn.setStyleSheet("background-color: #00BFFF;color:white")
        login_btn.setFixedHeight(40)
        form_layout.addRow(login_btn)
        v_layout.addLayout(form_layout)
        self.setLayout(v_layout)
        login_btn.clicked.connect(self.login_info)

        reg_btn = QPushButton('注册')
        reg_btn.setStyleSheet("background-color: #00BFFF;color:white")
        reg_btn.setFixedHeight(40)
        form_layout.addRow(reg_btn)
        v_layout.addLayout(form_layout)
        reg_btn.clicked.connect(lambda: stacked_widget.setCurrentWidget(self.regi_widget))

        self.login_widget = QWidget()
        self.login_widget.setStyleSheet('background-color:#EEE9E9;border-radius:5px')
        self.login_widget.setLayout(v_layout)

        # 设置注册窗口
        r_layout = QVBoxLayout()
        r_layout.setAlignment(Qt.AlignVCenter)
        form_layout = QFormLayout()
        label = QLabel('798登录注册')
        font = QFont()
        font.setPointSize(17)
        label.setFont(font)
        form_layout.addRow(label)
        # 设置颜色为灰色
        palette = label.palette()
        palette.setColor(QPalette.WindowText, Qt.gray)
        label.setPalette(palette)

        #  创建一条水平线
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setFrameShadow(QFrame.Shadow.Sunken)
        line.setStyleSheet('background-color:rgb(200, 200, 198)')
        line.setFixedHeight(1)  # 设置水平线的高度
        # 将水平线加到主窗口的中心布局中
        form_layout.addRow(line)

        self.uame = QLineEdit('')
        self.uame.setPlaceholderText('注册用户名')
        self.uame.setStyleSheet('background-color:#FFFFFF;color:gray;border:none;padding-left:5px;border-radius:5px')
        self.uame.setFixedHeight(20)
        form_layout.addRow(self.uame)
        self.pwd = QLineEdit('')
        self.pwd.setPlaceholderText("密码")
        self.pwd.setEchoMode(QLineEdit.Password)  # 密码加密
        self.pwd.setStyleSheet('background-color:#FFFFFF;color:gray; border:none;padding-left:5px;border-radius:5px')
        self.pwd.setFixedHeight(20)
        form_layout.addRow(self.pwd)
        self._pwd = QLineEdit('')
        self._pwd.setPlaceholderText("再次密码")
        self._pwd.setEchoMode(QLineEdit.Password)  # 密码加密
        self._pwd.setStyleSheet(
            'background-color:#FFFFFF;color:gray; border:none;padding-left:5px;border-radius:5px')
        self._pwd.setFixedHeight(20)
        form_layout.addRow(self._pwd)
        self.r_phone = QLineEdit('')
        self.r_phone.setPlaceholderText('手机号')
        self.r_phone.setStyleSheet('background-color:#FFFFFF;color:gray;border:none;padding-left:5px;border-radius:5px')
        self.r_phone.setFixedHeight(20)
        form_layout.addRow(self.r_phone)

        reg_btn = QPushButton('注册')
        reg_btn.setStyleSheet("background-color: #00BFFF;color:white")
        reg_btn.setFixedHeight(30)
        reg_btn.clicked.connect(self.regi)
        r_layout.addLayout(form_layout)
        form_layout.addRow(reg_btn)

        sign = QLabel("登录")
        sign.setFixedSize(28, 18)
        sign.setStyleSheet("color:black")
        sign.mousePressEvent = lambda event: stacked_widget.setCurrentWidget(self.login_widget)

        self.regi_widget = QWidget()
        self.regi_widget.setStyleSheet('background-color:#EEE9E9;border-radius:5px')
        self.regi_widget.setLayout(r_layout)
        r_layout.addWidget(sign)

        stacked_widget.addWidget(self.login_widget)
        stacked_widget.addWidget(self.regi_widget)

        self.setCentralWidget(stacked_widget)
        self.login_widget.setFixedSize(270, 300)
        self.regi_widget.setFixedSize(270, 300)


    def login_info(self):
        self.users = {
            "name": self.name.text(),
            "psssword": self.password.text()
        }
        msg = QMessageBox()
        user = self.session.query(User).filter(User.name == self.name.text(),User.password == self.password.text(),User.is_admin==1).first()
        print(user)

        try:
            if user:
                msg.information(self, "info", "用户是管理员，登陆成功")
                self.name.clear()
                self.password.clear()
                self.hide()
                self.win1 = MainWindow()
                self.win1.show()
            else:
                msg.warning(self, "警示", "用户不是管理员，请重新输入")
                self.name.clear()
                self.password.clear()
        except Exception as e:
            self.session.close()
            print("登录失败的原因是：% s" % e)

    def regi(self):
        current_time = datetime.datetime.now()
        format_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        print(format_time)
        uame = self.uame.text()
        pwd = self.pwd.text()
        conform_pwd = self._pwd.text()
        phone = self.r_phone.text()
        if pwd != conform_pwd:
            QMessageBox.warning(self, "密码不一样", "两次密码输入不一致")
        if uame == "":
            QMessageBox.warning(self, "警告", "用户名不能为空")
        if phone == "":
            QMessageBox.warning(self, "警告", "手机号不能为空")
        if not re.match(r"1[3-9]\d{9}", phone):
            QMessageBox.warning(self, "警告", "手机号格式不正确")

        self.mysql.insert_one_user([self.uame.text(), self.pwd.text(), self.r_phone.text(), 0, format_time])
        QMessageBox.information(self, "成功", "注册成功")
        # 关闭页面
        self.hide()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 创建窗口对象
    win = MyWidget()
    win.show()
    sys.exit(app.exec())